import { EChart, TEChartOptions } from "@/models/reactiveComponent";
import { computed, Ref, ref } from "vue";
import { create as createNormal, TChartCreator } from "./normalController";

import {
  TEchartEventParams,
  TEchartInstance,
  TServices,
  TPerformType,
} from "./types";

export type TController = ReturnType<typeof createController>;

export function createController(model: EChart, services: TServices) {
  const performType: TPerformType = ref("none");

  let ctrlers = [] as TChartCreator[];

  if (model.optionType === "dict") {
    ctrlers = model.chartInfos.map((info, idx) => {
      return createNormal(model, idx, performType, services);
    });
  }

  const curIndex = ref(0);
  const canBack = computed(() => curIndex.value > 0);
  const canForward = computed(() => curIndex.value < ctrlers.length - 1);
  const curController = computed(() => ctrlers[curIndex.value]);

  function next(
    echartIns: TEchartInstance,
    preChartParams: TEchartEventParams,
    preFilterValue: string
  ) {
    if (curController.value.hasClickInfo) {
      performType.value = "forward";
      curController.value.drillStartPos(echartIns);

      curIndex.value += 1;
      curController.value.setDataGroupValue(preFilterValue);
    }
  }

  function back(echartIns: TEchartInstance) {
    performType.value = "back";
    curController.value.drillStartPos(echartIns);

    curIndex.value -= 1;
    // curController.value.setDataGroupValue(params)
  }

  function back2start(echartIns: TEchartInstance) {
    for (let i = curIndex.value; i > 0; i--) {
      curController.value.removeFilter();
      back(echartIns);
    }

    curController.value.removeFilter();
  }

  function setSeriesKeys(echartIns: TEchartInstance, ids: string[]) {
    const opts = echartIns.getOption() as TEChartOptions;
    if (opts) {
      opts.series.forEach((s, idx) => {
        if ("universalTransition" in s) {
          if ("seriesKey" in s["universalTransition"]) {
            s.universalTransition["seriesKey"] = ids;
          }
        }

        delete s["dataGroupId"];
      });

      echartIns.setOption(opts);
    }
  }

  return {
    curController,
    next,
    canBack,
    canForward,
    back,
    back2start,
    setSeriesKeys,
  };
}
